# -*- coding: UTF-8 -*-
################################################################################
#
# Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
本文件实现了一个完整的demo
"""

from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from bottle import route, run, template, request


import multiprocessing
import sys

import cv2
import BaiduAI.EasyEdge as edge
import logging

edge.Log.set_level(logging.INFO)

_model_dir = '/opt/py/baidu/RES/'
_test_img = '/opt/py/baidu/python/20190624_162913.jpg'
_test_round = 1


edge.set_auth_license_key("2F70-2FAB-53E7-F35D")


@route('/hello/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!', name=name)




@route('/hello2',  method='POST')
def test():
	
    """单进程"""
    line_color = (125, 175, 75)

    print(request.forms.get('jay'))
    pred = edge.Program()
    # 使用CPU
    pred.init(model_dir=_model_dir, device=edge.Device.CPU, engine=edge.Engine.PADDLE_FLUID)

    # 使用GPU
    # pred.init(model_dir=_model_dir, device=edge.Device.GPU, engine=edge.Engine.PADDLE_FLUID)

    img = cv2.imread(_test_img)
    for i in range(_test_round):
        res = pred.infer_image(img, 0.1)
        h, w, _ = img.shape
        for r in res:
            if pred.model_type == edge.c.ModelType.ObjectDetection:
                x1 = int(r['x1'] * w)
                y1 = int(r['y1'] * h)
                x2 = int(r['x2'] * w)
                y2 = int(r['y2'] * h)
                cv2.rectangle(img, (x1, y1), (x2, y2), line_color, 2)
                cv2.putText(
                    img=img, text=r['label'], org=(x1, y1),
                    fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=1, color=line_color, thickness=1
                )
            print(r)
        # cv2.imshow("Edge", img)
        cv2.imwrite(_test_img + ".result.jpg", img)
    pred.close()
    return 'ok'

run(host='localhost', port=8082)

# def test_multi_ncs():
#     """同时使用多个设备"""
#     q = multiprocessing.Queue(maxsize=100)
#
#     img = cv2.imread(_test_img)
#
#     def _task(i):
#         print("Process %d started" % i)
#         pred = edge.Program()
#         pred.init(model_dir=_model_dir, device=edge.Device.CPU, engine=edge.Engine.PADDLE_FLUID)
#
#         while True:
#             try:
#                 img = q.get(block=True, timeout=1)
#                 print("Process", i, pred.infer_image(img))
#             except Exception as e:
#                 break
#
#         pred.close()
#
#     p1 = multiprocessing.Process(target=_task, args=[1])
#     p2 = multiprocessing.Process(target=_task, args=[2])
#
#     p1.start()
#     p2.start()
#
#     for i in range(_test_round):
#         q.put(img)
#
#     p1.join()
#     p2.join()


#if __name__ == '__main__':
#    test()


